/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ImportarDados.java
 *
 * Created on 27/05/2010, 18:34:56
 */

package gerenciadorfinanceiro.view.resources;

import gerenciadorfinanceiro.Utilitario;
import gerenciadorfinanceiro.database.resources.Income;
import gerenciadorfinanceiro.database.resources.Outcome;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;
import org.jdesktop.application.Action;

/**
 *
 * @author eduardo
 */
public class ImportarDados extends javax.swing.JDialog {

    /** Creates new form ImportarDados */
    public ImportarDados(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblArquivo = new javax.swing.JLabel();
        txtArquivo = new javax.swing.JTextField();
        btnSelecionar = new javax.swing.JButton();
        btnProcessar = new javax.swing.JButton();
        btnLimpar = new javax.swing.JButton();
        lblMensagem = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gerenciadorfinanceiro.GerenciadorFinanceiroApp.class).getContext().getResourceMap(ImportarDados.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setModal(true);
        setName("Form"); // NOI18N
        setResizable(false);

        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        jPanel1.setName("jPanel1"); // NOI18N

        lblArquivo.setText(resourceMap.getString("lblArquivo.text")); // NOI18N
        lblArquivo.setName("lblArquivo"); // NOI18N

        txtArquivo.setBackground(resourceMap.getColor("txtArquivo.background")); // NOI18N
        txtArquivo.setEditable(false);
        txtArquivo.setText(resourceMap.getString("txtArquivo.text")); // NOI18N
        txtArquivo.setName("txtArquivo"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gerenciadorfinanceiro.GerenciadorFinanceiroApp.class).getContext().getActionMap(ImportarDados.class, this);
        btnSelecionar.setAction(actionMap.get("SelecionarArquivo")); // NOI18N
        btnSelecionar.setText(resourceMap.getString("btnSelecionar.text")); // NOI18N
        btnSelecionar.setName("btnSelecionar"); // NOI18N

        btnProcessar.setAction(actionMap.get("ProcessarImportacao")); // NOI18N
        btnProcessar.setText(resourceMap.getString("btnProcessar.text")); // NOI18N
        btnProcessar.setEnabled(false);
        btnProcessar.setName("btnProcessar"); // NOI18N

        btnLimpar.setAction(actionMap.get("Limpar")); // NOI18N
        btnLimpar.setText(resourceMap.getString("btnLimpar.text")); // NOI18N
        btnLimpar.setEnabled(false);
        btnLimpar.setName("btnLimpar"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btnProcessar, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblArquivo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSelecionar, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSelecionar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnProcessar)
                    .addComponent(btnLimpar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        lblMensagem.setText(resourceMap.getString("lblMensagem.text")); // NOI18N
        lblMensagem.setName("lblMensagem"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblMensagem, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblMensagem)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void SelecionarArquivo() {
        JFileChooser escolha = new JFileChooser();
        int opcao = escolha.showOpenDialog(jPanel1);

        if (opcao == JFileChooser.APPROVE_OPTION) {
            txtArquivo.setText(escolha.getSelectedFile().getAbsolutePath());
            btnSelecionar.setEnabled(false);
            btnProcessar.setEnabled(true);
        }
    }

    @Action
    public void ProcessarImportacao() {
        try {
                BufferedReader in = new BufferedReader(new FileReader(txtArquivo.getText()));
            String str;
            str = in.readLine();

            while (in.ready()) {
                str = in.readLine();
                StringTokenizer token = new StringTokenizer(str, ",");

                token.nextToken();
                Date data = DateFormat.getDateInstance(DateFormat.SHORT, new Locale("pt","br")).parse(token.nextToken());

                double valor = Double.parseDouble(token.nextToken());
                token.nextToken();
                String descricao = token.nextToken();
                String categoria = token.nextToken();

                if (valor > 0) {
                    Income income = new Income();
                    income.setData(data);
                    income.setDescriptionIncome(descricao);
                    income.setValue(valor);
                    income.setOwner(util.getLoggedUser());

                    util.getIncomeDAO().saveIncome(income);
                } else {
                    Outcome outcome = new Outcome();
                    outcome.setData(new Date());
                    outcome.setDescriptionOutcome(descricao);
                    outcome.setExpirationData(data);
                    outcome.setOwner(util.getLoggedUser());
                    outcome.setValue(valor*(-1));
                    outcome.setSource(util.getOutcomeSourceDAO().getSourceByName(categoria));

                    util.getOutcomeDAO().gravaOutcome(outcome);
                }

            }
            in.close();
            lblMensagem.setText("Arquivo importado com sucesso !");
        } catch (Exception exc) {
            lblMensagem.setText("Erro: "+exc.getMessage());
        }

    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnProcessar;
    private javax.swing.JButton btnSelecionar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblArquivo;
    private javax.swing.JLabel lblMensagem;
    private javax.swing.JTextField txtArquivo;
    // End of variables declaration//GEN-END:variables

    private Utilitario util;

    public Utilitario getUtil() {
        return util;
    }

    public void setUtil(Utilitario util) {
        this.util = util;
    }

    public ImportarDados() {
        initComponents();
    }

    @Action
    public void Limpar() {
        btnSelecionar.setEnabled(true);
        txtArquivo.setText("");
        btnProcessar.setEnabled(false);
    }

    

}
